package com.um.psystem.controller.sop;

import com.um.psystem.controller.BaseController;
import com.um.psystem.entity.mtEntity.AssetsType;
import com.um.psystem.entity.sopEntity.SOPUpdateDtl;
import com.um.psystem.enums.ResponseEnum;
import com.um.psystem.model.vo.DataGrid;
import com.um.psystem.model.vo.JsonResult;
import com.um.psystem.router.BaseRouter;
import com.um.psystem.service.sopService.ISOPDownloadService;
import com.um.psystem.service.sopService.ISOPUpdateService;
import com.um.psystem.utils.MyfileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @Auther: QY
 * @Date: 2021/09/06 - 20:44
 * @Description: com.um.psystem.controller.sop
 * @version: 1.0
 */
@Controller
@RequestMapping(value = "/sop")
public class SOPController extends BaseController {
    @Autowired
    ISOPUpdateService isopUpdateService;
    @Autowired
    ISOPDownloadService isopDownloadService;

    /**
     * 查询记录表信息
     *
     * @return
     */
    @RequestMapping(value = "/sopRecordListGrid", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getSopRecordList(@RequestParam Map map) {
        List<Map<String, Object>> assetsTypeList = isopUpdateService.getSopRecordList(map);
        int count = 0;
        if (assetsTypeList != null && assetsTypeList.size() > 0)
            count = Integer.parseInt(assetsTypeList.get(0).get("totals").toString());
        return buildDataGrid(assetsTypeList, count);
    }

    /**
     * 删除记录(可以删除多条)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleRecordInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleSOPRecord(@RequestParam Map map) {
        Integer id = Integer.parseInt(map.get("id").toString());
        String url = map.get("download_url").toString();
        String name = map.get("name").toString();
        if (name.equals("机型"))
        {isopUpdateService.deleMachineTypeSOPRecord(id,url);}
        else
        {isopUpdateService.deleSOPRecord(id,url);}
        return JsonResult.success(ResponseEnum.SUCCESS);
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult upload(@RequestParam("files") MultipartFile[] files, ModelMap map, @RequestParam Map map_id) {
        String username = map_id.get("username").toString();
        String fileName = "";
        String[] fileNameAra = null;
        String dir1 = "";
        String dir2 = "";
        for (MultipartFile file : files) {
            fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
            System.out.println("fileName:"+fileName);
        }

        if (map_id.get("uploadType").toString().equals("0"))
        {
            if(fileName.substring(0, 1).equals("W")){
                dir1 = fileName.substring(0, 1);
            }else if(fileName.substring(0, 1).equals("V")){
                dir1 = fileName.substring(0, 2);
            }else if(fileName.contains("通用")){
                dir1 = "通用";
            }else{
                return JsonResult.error(400,"SOP物料编码不符合要求");
            }
            fileNameAra = fileName.split("_");
            JsonResult<Integer> integerJsonResult = isopUpdateService.checkFileName(fileNameAra);
            if(!(integerJsonResult.getCode()==200)){
                return integerJsonResult;
            }
            if (!dir1.equals("通用")) {
                dir2 = fileNameAra[0] + "/" + fileNameAra[1];
            }
            String dir = dir1+"/"+dir2;
            //清空指定目录（保证上传的是最新的文件）
    //        String path = MyfileUtils.directory+"/SOP/" + dir;
    //        File file = new File(path);//创建文件类，指定要删除的文件夹路径
    //        MyfileUtils.remove(file);//删除文件夹下内容
    //        file.delete();//删除根目录,即要清空的那个文件夹
    //        if (!file.exists()) {
    //            System.out.println("删除成功");
    //        }
            List<String> results = MyfileUtils.uploadFileSOP(files, dir, null,0);
            if (results != null && results.size() > 0) {
                map.addAttribute("urls", results.get(0));
                if (!dir1.equals("通用")){
                    return isopUpdateService.addSOPRecord(map_id,fileNameAra,dir1,results.get(0));
                }else{
                    return isopUpdateService.addSOPRecordByCurrent(map_id,fileNameAra,dir1,results.get(0));
                }

            } else {
                return JsonResult.error(400,"文件上传失败");
            }
        }
        else
        {
            fileNameAra = fileName.split("_");
            JsonResult<Integer> integerJsonResult = isopUpdateService.checkModelSopFileName(fileNameAra);
            if(!(integerJsonResult.getCode()==200)){
                return integerJsonResult;
            }
            String dir = fileNameAra[0] + "/" + fileNameAra[1];

            List<String> results = MyfileUtils.uploadFileSOP(files, dir, null,1);
            if (results != null && results.size() > 0) {

                map.addAttribute("urls", results.get(0));
                return isopUpdateService.addSOPRecordByMachineType(map_id,fileNameAra,results.get(0));

            } else {
                return JsonResult.error(400,"文件上传失败");
            }
        }

    }

    /**
     * 获取Sop下载列表(分页)
     *
     * @return
     */
    @RequestMapping(value = "/getSopRecordDownloadList", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getSopRecordDownloadList(@RequestParam Map map) {
        List<Map<String, Object>> SopRecordList = isopDownloadService.getSopRecordListByBomNum(map);
        System.out.println(SopRecordList.size());
        int count = 0;
        if (SopRecordList != null && SopRecordList.size() > 0)
            count = Integer.parseInt(SopRecordList.get(0).get("totals").toString());
        return buildDataGrid(SopRecordList, count);
    }

    /**
     * 获取Sop机型下载列表(分页)
     *
     * @return
     */
    @RequestMapping(value = "/getModelRecordDownloadList", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getModelRecordDownloadList(@RequestParam Map map) {
        List<Map<String, Object>> SopRecordList = isopDownloadService.getModelRecordListByModelName(map);
        System.out.println(SopRecordList.size());
        int count = 0;
        if (SopRecordList != null && SopRecordList.size() > 0)
            count = Integer.parseInt(SopRecordList.get(0).get("totals").toString());
        return buildDataGrid(SopRecordList, count);
    }

    @RequestMapping(value = "/exportSOPRelationshipData",method = RequestMethod.GET)
    public void exportSOPRelationshipData(HttpServletResponse response,@RequestParam Map map)
    {
        System.out.println(map);
        isopDownloadService.exportSOPRelationshipData(response,map);
    }
}
